package com.peak.distribution.web.validator.method;

import java.util.Map;

import com.peak.distribution.web.validator.ValidateRuleMethod;
import com.peak.spring.boot.tools.Converts;

public class Length implements ValidateRuleMethod {

	private Integer min;
	
	private Integer max;
	
	private String errorMessage;

	@Override
	public boolean execute(Object value) {
		int lng = Converts.toString(value).length();
		boolean result = true;
		if (min == null && max == null) {
			result = true;// 相当于不限制
		} else if (min != null && max == null) {
			if (lng < min) {
				result = false;
				this.errorMessage = "{0}的长度不能少于" + min + "个";
			}
		} else if (min == null && max != null) {
			if (lng > max) {
				result = false;
				this.errorMessage = "{0}的长度不能大于" + max + "个";
			}
		} else {
			if (lng < min || lng > max) {
				result = false;
				this.errorMessage = "{0}的长度应在" + min + "和" + max + "之间";
			}
		}
		return result;
	}

	@Override
	public String getErrorMessageTemplate() {
		return this.errorMessage;
	}

	@Override
	public void setParams(Map<String, Object> param) {
		this.min = Converts.toInteger(param.get("min"));
		this.max = Converts.toInteger(param.get("max"));
	}
}
